package com.xiaoming.mojcodesandbox.utils;

import com.xiaoming.mojcodesandbox.model.ExecuteMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 执行进程并获取信息
 */
public class ProcessUtils {
    public static ExecuteMessage runProcessAndGetMessage(Process process,String operationName)
    {

        ExecuteMessage executeMessage=new ExecuteMessage();
        try {
            StopWatch stopWatch=new StopWatch();
            stopWatch.start();
            int exitValue=process.waitFor();
            if(exitValue==0)
            {
                //编译正常
                System.out.println(operationName+"成功");
                List<String> outputStrList=new ArrayList<>();
                //获取进程则正常输出
                BufferedReader bufferedReader =new BufferedReader( new InputStreamReader(process.getInputStream()));
                String compileOutputLine;
                while ((compileOutputLine = bufferedReader.readLine())!=null)
                {
                    outputStrList.add(compileOutputLine);
                }
                executeMessage.setMessage(StringUtils.join(outputStrList,"\n"));
            }
            else
            {
                //编译错误
                System.out.println(operationName+"失败，错误码："+exitValue);
                List<String> outputStrList=new ArrayList<>();
                //获取进程则正常输出
                BufferedReader bufferedReader =new BufferedReader( new InputStreamReader(process.getInputStream()));
                String compileOutputLine;
                while ((compileOutputLine = bufferedReader.readLine())!=null)
                {
                    outputStrList.add(compileOutputLine);
                }
                executeMessage.setMessage(StringUtils.join(outputStrList,"\n"));
                //获取进程错误输出
                List<String> errOutputStrList=new ArrayList<>();
                String errorOutputLine;
                BufferedReader errprBufferedReader =new BufferedReader( new InputStreamReader(process.getErrorStream()));
                while ((errorOutputLine = errprBufferedReader.readLine())!=null)
                {
                    errOutputStrList.add(errorOutputLine);
                }
                executeMessage.setErrorMessage(StringUtils.join(errOutputStrList,"\n"));

            }
            stopWatch.stop();
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());

        }catch (Exception e)
        {
            e.printStackTrace();
        }

        executeMessage.setExitValue(process.exitValue());

        return executeMessage;

    }

}
